//
//  ZMYReadViewController.m
//  奇阅
//
//  Created by 奇阅科技 on 14-10-15.
//  Copyright (c) 2014年 奇阅科技. All rights reserved.
//

#import "ZMYReadViewController.h"
#import "ZoomTransitionProtocol.h"
#import "UIViewControllerAdditions.h"
#import "ZMYcatalogueRootViewController.h"
#import "BookReadDownloadViewController.h"
#import "BookThemeCommentListViewController.h"
#import "ReadConfig.h"
#import "ModelController.h"
#import "ReadPageViewController.h"
#import "ZMYAutoReadViewController.h"
#import "TaskList.h"
#import "BookReadPermissions.h"
#import "PayWebView.h"
#import "SIDownloadManager.h"
#import "SIBreakpointsDownload.h"
#import "DefaultSubscription.h"
#import "YiDongSubscription.h"
@interface ZMYReadViewController ()<ZoomTransitionProtocol,ReadPageTextViewDelegate,AutoReadTextViewDelegate,PayWebViewDelegate>
{
    BookReadDownloadViewController *bookReadDownloadViewController;
    NSInteger currentInt;
    BOOL isAutoScroll;//是否是在自动滚动，
    NSString *currentRangStr;
    NSMutableArray *chapterArray;
}
@property(nonatomic, weak) id<UIViewControllerTransitioningDelegate> delegate;
@property (nonatomic, assign) BOOL isFirstIn;
@property (nonatomic, strong) UIButton *bookMarkButton;
@property (nonatomic, strong) UIButton *shareButton;
@property (nonatomic, strong) UIButton *commentButton;
@property (nonatomic,strong)ZMYAutoReadViewController *autoReadViewController;
@property (readonly, strong, nonatomic) ModelController *modelController;
@property (weak,nonatomic)MBProgressHUD *progressHud;
@end

@implementation ZMYReadViewController
@synthesize modelController = _modelController;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    NSLog(@"阅读页释放了");
}
-(void)loadView{
    [super loadView];
    self.imageView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    self.groundView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO; 
    // Do any additional setup after loading the view.
    _isFirstIn = YES;
    [self setLeftButtonForNavigation:@"BackBtn.png" selector:@selector(backToRack)];
    [self setBarBackgroundImage:@"ReadViewNav"];
    self.imageView.image = self.image;
    chapterArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[[PathHelper documentDirectoryPathWithName:@"db"]
                                                                               stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ChapterInfo",self.book.articleid]]];
    
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"SliderButton"] forState:UIControlStateNormal];
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"SliderButton"] forState:UIControlStateHighlighted];
    [self.lightSlider setThumbImage:[UIImage imageNamed:@"SliderButton"] forState:UIControlStateNormal];
    [self.lightSlider setThumbImage:[UIImage imageNamed:@"SliderButton"] forState:UIControlStateHighlighted];
    [self.scrollSpeedSlider setThumbImage:[UIImage imageNamed:@"SliderButton"] forState:UIControlStateNormal];
    [self.scrollSpeedSlider setThumbImage:[UIImage imageNamed:@"SliderButton"] forState:UIControlStateHighlighted];
    self.bigBottomViewBottomConstraint.constant = -205;
    self.smallBottomViewBottomConstraint.constant = -142;
    self.autoScrollViewBottomConstraint.constant = -150;
    
    if ([ReadConfig currentAccount].isBlack) {
        [self.linghtButton setImage:[UIImage imageNamed:@"textColorDay"] forState:UIControlStateNormal];
    }else{
        [self.linghtButton setImage:[UIImage imageNamed:@"textColorNight"] forState:UIControlStateNormal];
    }
    
    _bookMarkButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_bookMarkButton setFrame:CGRectMake(0.0f, 0.0f, 30.0f, 30.0f)];
    [_bookMarkButton setImage:[UIImage imageNamed:@"bookMarkNor"] forState:UIControlStateNormal];
    [_bookMarkButton addTarget:self action:@selector(saveBookmark) forControlEvents:UIControlEventTouchUpInside];
    _bookMarkButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    _bookMarkButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    UIBarButtonItem *bookMarkButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_bookMarkButton];
    
    _shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_shareButton setFrame:CGRectMake(0.0f, 0.0f, 40.0f, 30.0f)];
    [_shareButton setImage:[UIImage imageNamed:@"bookShare"] forState:UIControlStateNormal];
    [_shareButton addTarget:self action:@selector(shareBook) forControlEvents:UIControlEventTouchUpInside];
    _shareButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    _shareButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    UIBarButtonItem *shareButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_shareButton];
    
    _commentButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_commentButton setFrame:CGRectMake(0.0f, 0.0f, 50.0f, 30.0f)];
    [_commentButton setBackgroundImage:[UIImage imageNamed:@"bookComment"] forState:UIControlStateNormal];
    [_commentButton addTarget:self action:@selector(commentBook) forControlEvents:UIControlEventTouchUpInside];
    _commentButton.titleLabel.font = [UIFont systemFontOfSize:12.0f];
    _commentButton.titleEdgeInsets = UIEdgeInsetsMake(-4, 0, 0, 0);
    if ([self.book.bookCommentNum integerValue]<1) {
        [_commentButton setTitle:@"0书评" forState:UIControlStateNormal];
    }else{
        [_commentButton setTitle:[NSString stringWithFormat:@"%@书评",self.book.bookCommentNum] forState:UIControlStateNormal];
    }
    UIBarButtonItem *commentButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_commentButton];
    
    self.navigationItem.rightBarButtonItems = @[commentButtonItem,shareButtonItem,bookMarkButtonItem];
    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(barHidden)];
//    [self.middleTouchButton addGestureRecognizer:tap];
    
    self.animator = [ZMYAnimator new];
    [self changeToReadSchedule];
    __weak typeof(self) weakSelf = self;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeToReadSchedule) name:@"ToBeforChapter" object:nil];
//    [[NSNotificationCenter defaultCenter]addObserverForName:@"ToBeforChapter" object:self queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
//        NSLog(@"接收到通知");
//        [weakSelf changeToReadSchedule];
//    }];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(backToRack) name:@"ToBookRack" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserverForName:@"HidenReadNav" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        if ((!weakSelf.isFirstIn) && (!weakSelf.navigationController.navigationBarHidden)) {
            [weakSelf barHidden];
        }
    }];
    if ([self.book.articleid hasPrefix:@"qiyou"]) {
        self.chapterCacheButton.hidden = YES;
    }
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setBarBackgroundImage:@"ReadViewNav"];
    //设置屏幕不锁屏
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    [self updateBookmarkImage:currentRangStr];
    
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.imageView.hidden = YES;
    if (self.isFirstIn) {
        //打开书本的时候隐藏导航条。如果放在viewWillAppear里面会出现蓝色背景色
        [self barHidden];
        self.isFirstIn = NO;
    }
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.imageView.hidden = NO;
    ReadPageViewController *currentViewController = self.pageViewController.viewControllers.lastObject;
    if (currentViewController.readSchedule) {
        [[ZMYLKDB getLKDBHelper] updateReadSchedule:currentViewController.readSchedule];
    }
    //设置屏幕锁屏
    [UIApplication sharedApplication].idleTimerDisabled = NO;
}
#pragma mark - 切换到当前阅读进度
-(void)changeToReadSchedule{
//    if ((self.pageViewController==nil) || ([ReadConfig currentAccount].transitionStyle!=self.pageViewController.transitionStyle)) {
        for (id view in self.groundView.subviews) {
            if ([view isKindOfClass:[UIView class]]) {
                if (view == self.pageViewController.view) {
                    [view removeFromSuperview];
//                    break;
                }
            }
        }
    if (self.pageViewController) {
//        [self.pageViewController willMoveToParentViewController:nil];
//        [self.pageViewController.view removeFromSuperview];
//        [self.pageViewController removeFromParentViewController];
//        self.pageViewController.delegate = nil;
//        self.pageViewController.dataSource = nil;
//        self.pageViewController = nil;
        _modelController = nil;
//        self.view.gestureRecognizers = nil;
    }
        UIPageViewControllerTransitionStyle transitionStyle=[ReadConfig currentAccount].transitionStyle?UIPageViewControllerTransitionStyleScroll:UIPageViewControllerTransitionStylePageCurl;
        self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:transitionStyle navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
        NSRange rang = NSRangeFromString([[ZMYLKDB getLKDBHelper]getReadSchedule:self.book.articleid].rang);
        NSInteger item = [self.modelController getIndexItem:rang];
        ReadPageViewController *startingViewController = [self.modelController viewControllerAtIndex:item storyboard:self.storyboard];
        NSArray *viewControllers = @[startingViewController];

        [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
        
        self.pageViewController.delegate = self;
        self.pageViewController.dataSource = self.modelController;
        
        [self addChildViewController:self.pageViewController];
        [self.groundView addSubview:self.pageViewController.view];
        CGRect pageViewRect = self.view.bounds;
        self.pageViewController.view.frame = pageViewRect;
        [self.pageViewController didMoveToParentViewController:self];
        self.view.gestureRecognizers = self.pageViewController.gestureRecognizers;
        
//    }else{
//        _modelController = nil;
//        self.pageViewController.dataSource = nil;
//        ;
//        self.pageViewController.delegate = nil;
//        
//        NSRange rang = NSRangeFromString([[ZMYLKDB getLKDBHelper]getReadSchedule:self.book.articleid].rang);
//        NSInteger item = [self.modelController getIndexItem:rang];
//        ZMYReadPageViewController *startingViewController = [self.modelController viewControllerAtIndex:item storyboard:self.storyboard];
//        NSArray *viewControllers = @[startingViewController];
//        [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
//        self.pageViewController.dataSource = self.modelController;
//        self.pageViewController.delegate = self;
//    }
    [self changePageSlile];
}

#pragma mark - 更新书签按钮图标
-(void)updateBookmarkImage:(NSString *)rangStr{
    currentRangStr = rangStr;
    NSArray *bookmarks = [[ZMYLKDB getLKDBHelper]getBookmarkChapterId:[self currentChapterInfo].chapterId];
    for (Bookmark *bookmark in bookmarks) {
        if (NSIntersectionRange(NSRangeFromString(bookmark.rang), NSRangeFromString(rangStr)).length>0) {
            [_bookMarkButton setImage:[UIImage imageNamed:@"bookMarkNorSel"] forState:UIControlStateNormal];
//            _bookMarkButton.userInteractionEnabled = NO;
            return;
        }
    }
    [_bookMarkButton setImage:[UIImage imageNamed:@"bookMarkNor"] forState:UIControlStateNormal];
    _bookMarkButton.userInteractionEnabled = YES;
    return;
}

-(BookChapterInfo *)beforeChapterInfo{
    [self currentChapterInfo];
    if (currentInt>0) {
        _beforeChapterInfo = [chapterArray objectAtIndex:currentInt-1];
    }else{
        _beforeChapterInfo = nil;
    }
    return _beforeChapterInfo;
}
-(BookChapterInfo *)currentChapterInfo{
    _currentChapterInfo = [chapterArray objectAtIndex:0];
    ReadSchedule  *readSc = [[ZMYLKDB getLKDBHelper]getReadSchedule:self.book.articleid];
    if (readSc) {
        for (BookChapterInfo *chapterInfo in chapterArray) {
            if ([chapterInfo.chapterId isEqualToString:readSc.chapterId]) {
                _currentChapterInfo = chapterInfo;
                currentInt = [chapterArray indexOfObject:chapterInfo];
                break;
            }
        }
    }
    return _currentChapterInfo;
}
-(BookChapterInfo *)nextChapterInfo{
    [self currentChapterInfo];
    if (currentInt<chapterArray.count-1) {
        _nextChapterInfo = [chapterArray objectAtIndex:currentInt+1];
    }else{
        _nextChapterInfo = nil;
    }
    return _nextChapterInfo;
}
- (ModelController *)modelController {
    @synchronized(self) {
        // 需要锁定的代码
        if (!_modelController) {
            _modelController = [[ModelController alloc] init];
            _modelController.book = self.book;
            _modelController.delegate = self;
            [_modelController parseBookChapterText];
        }
    }
    return _modelController;
}

#pragma mark - UIPageViewController delegate methods

- (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation {
    // Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to YES, so set it to NO here.
//    UIViewController *currentViewController = self.pageViewController.viewControllers[0];
//    NSArray *viewControllers = @[currentViewController];
//    [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
//    
//    self.pageViewController.doubleSided = NO;
    return UIPageViewControllerSpineLocationMin;
}
#pragma mark - ReadPageTextViewDelegate 中间区域和左右区域点击时间
-(void)clickMiddleDetect{
    [self barHidden];
}
-(void)clickRightDetect{
    [self barHidden];
}
-(void)clickLeftDetect{
    [self barHidden];
}
#pragma mark - 保存书签
-(void)saveBookmark{
    NSArray *bookmarks = [[ZMYLKDB getLKDBHelper]getBookmarkChapterId:[self currentChapterInfo].chapterId];
    for (Bookmark *bookmark in bookmarks) {
        if (NSIntersectionRange(NSRangeFromString(bookmark.rang), NSRangeFromString(currentRangStr)).location!=NSNotFound) {
            [[ZMYLKDB getLKDBHelper]deleteToBookmarkDB:bookmark];
            [_bookMarkButton setImage:[UIImage imageNamed:@"bookMarkNor"] forState:UIControlStateNormal];
            return;
        }
    }
    Bookmark *bookmark = [Bookmark new];
    bookmark.articleid = self.book.articleid;
    bookmark.chapterId = [self currentChapterInfo].chapterId;
    bookmark.rang = currentRangStr;
    BookChapterText *chaptext = [[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:bookmark.articleid chapterId:bookmark.chapterId];
    bookmark.textString = [chaptext.chapterTextString substringWithRange:NSRangeFromString(bookmark.rang)];
    [[ZMYLKDB getLKDBHelper]insertToBookmarkDB:bookmark];
    [_bookMarkButton setImage:[UIImage imageNamed:@"bookMarkNorSel"] forState:UIControlStateNormal];
}
#pragma mark 分享
-(void)shareBook{
    if (self.book.bookAbout.length>100) {
        self.book.bookAbout = [self.book.bookAbout substringToIndex:100];
    }
    [UMSocialSnsService presentSnsIconSheetView:self appKey:nil shareText:self.book.bookAbout shareImage:nil shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQQ,UMShareToQzone,UMShareToDouban,UMShareToRenren,UMShareToSms,nil] delegate:self];
    UMSocialUrlResource *urlResource = [[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeImage url:self.book.imagefname];
    [UMSocialData defaultData].extConfig.sinaData.shareText = [NSString stringWithFormat:@"《%@》%@http://dataapi.yuewen.cc/web/store.php?a=fenxiang&bookid=%@",self.book.title,self.book.bookAbout,self.book.articleid];
    [UMSocialData defaultData].extConfig.sinaData.urlResource = urlResource;
    [UMSocialData defaultData].extConfig.wechatSessionData.url = [NSString stringWithFormat:@"http://dataapi.yuewen.cc/web/store.php?a=fenxiang&bookid=%@",self.book.articleid];
    [UMSocialData defaultData].extConfig.wechatSessionData.title = [NSString stringWithFormat:@"《%@》",self.book.title];
    [UMSocialData defaultData].extConfig.wechatSessionData.urlResource = urlResource;
    [UMSocialData defaultData].extConfig.wechatTimelineData.url = [NSString stringWithFormat:@"http://dataapi.yuewen.cc/web/store.php?a=fenxiang&bookid=%@",self.book.articleid];
    [UMSocialData defaultData].extConfig.wechatTimelineData.title = [NSString stringWithFormat:@"《%@》%@",self.book.title,self.book.bookAbout];
    [UMSocialData defaultData].extConfig.wechatTimelineData.urlResource = urlResource;
    [UMSocialData defaultData].extConfig.qqData.url = [NSString stringWithFormat:@"http://dataapi.yuewen.cc/web/store.php?a=fenxiang&bookid=%@",self.book.articleid];
    [UMSocialData defaultData].extConfig.qqData.title = [NSString stringWithFormat:@"《%@》",self.book.title];
    [UMSocialData defaultData].extConfig.qqData.urlResource = urlResource;
    [UMSocialData defaultData].extConfig.qzoneData.url = [NSString stringWithFormat:@"http://dataapi.yuewen.cc/web/store.php?a=fenxiang&bookid=%@",self.book.articleid];
    [UMSocialData defaultData].extConfig.qzoneData.title = [NSString stringWithFormat:@"《%@》",self.book.title];
    [UMSocialData defaultData].extConfig.qzoneData.urlResource = urlResource;
    
    [UMSocialData defaultData].extConfig.doubanData.shareText = [NSString stringWithFormat:@"《%@》%@http://dataapi.yuewen.cc/web/store.php?a=fenxiang&bookid=%@",self.book.title,self.book.bookAbout,self.book.articleid];
    [UMSocialData defaultData].extConfig.renrenData.shareText = [NSString stringWithFormat:@"《%@》%@http://dataapi.yuewen.cc/web/store.php?a=fenxiang&bookid=%@",self.book.title,self.book.bookAbout,self.book.articleid];
    [UMSocialData defaultData].extConfig.smsData.shareText = [NSString stringWithFormat:@"《%@》%@http://dataapi.yuewen.cc/web/store.php?a=fenxiang&bookid=%@",self.book.title,self.book.bookAbout,self.book.articleid];
}
-(BOOL)isDirectShareInIconActionSheet
{
    return YES;
}
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        TaskList *taskList = [TaskList currentAccount];
        Task *task = taskList.taskArray[3];
        if (!task.isFinshed) {
            task.isFinshed = YES;
            [TaskList saveAccount:taskList];
            [[ZMYNetWorkAPI default]taskFinsh];
        }
//        [AppDelegate showHUDAndHide:[NSString stringWithFormat:@"分享到%@成功！",[[response.data allKeys] objectAtIndex:0]] view:self.view];
//        [AppDelegate showHUDAndHide:@"分享到成功！" view:self.view];
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}
#pragma mark 评论
-(void)commentBook{
    BookThemeCommentListViewController *view = [[UIStoryboard storyboardWithName:@"BookShop" bundle:nil]instantiateViewControllerWithIdentifier:@"BookThemeCommentListViewController"];
    view.book = self.book;
    [self.navigationController pushViewController:view animated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(UIView *)viewForZoomTransition
{
    return self.imageView;
}
-(UIView *)firstViewForZoomTransition{
    return self.imageView;
}
-(UIView *)secondViewForZoomTransition{
    return self.groundView;
}
-(void)backToRack{
    [[ZMYNetWorkAPI default]cancelAllPermissionNetworkOperation];
    [[ZMYNetWorkAPI default]cancelAllChargeNetworkOperation];
    if (!self.navigationController.navigationBarHidden) {
        [UIView animateWithDuration:0.3 animations:^{
            if (isAutoScroll) {
                if (self.autoScrollViewBottomConstraint.constant<-10) {
                    self.autoScrollViewBottomConstraint.constant=0;
                    [self.autoScrollBottomView layoutIfNeeded];
                }
            } else {
                if (self.smallBottomView.frame.origin.y>SCREEN_HEIGHT-10) {
                    self.smallBottomViewBottomConstraint.constant = 0;
                    [self.smallBottomView layoutIfNeeded];
                }
            }
            
        } completion:^(BOOL finished) {
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }

    
}
#pragma mark - 显示调整字体大小View
-(void)barHidden{
    //根据导航条的显示和隐藏来调整菜单的
    if (self.navigationController.navigationBarHidden) {
        //显示导航条
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        [UIView animateWithDuration:0.3 animations:^{
            if (isAutoScroll) {
                if (self.autoScrollViewBottomConstraint.constant<-10) {
                    self.autoScrollViewBottomConstraint.constant=0;
                    [self.autoScrollBottomView layoutIfNeeded];
                }
            } else {
                if (self.smallBottomView.frame.origin.y>SCREEN_HEIGHT-10) {
                    self.smallBottomViewBottomConstraint.constant = 0;
                    [self.smallBottomView layoutIfNeeded];
                }
            }
            
        } completion:^(BOOL finished) {
        }];
    } else {
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        [UIView animateWithDuration:0.3 animations:^{
            if (self.smallBottomView.frame.origin.y<SCREEN_HEIGHT-10) {
                self.smallBottomViewBottomConstraint.constant = -142;
                [self.smallBottomView layoutIfNeeded];
            }
            if (self.bigBottomView.frame.origin.y<SCREEN_HEIGHT-10) {
                self.bigBottomViewBottomConstraint.constant = -205;
                [self.bigBottomView layoutIfNeeded];
            }
            if (self.autoScrollViewBottomConstraint.constant>-10) {
                self.autoScrollViewBottomConstraint.constant = -100;
                [self.autoScrollBottomView layoutIfNeeded];
            }
        } completion:^(BOOL finished) {
        }];
    }
}
#pragma mark 显示调整字体大小View
- (IBAction)showBigBottomView:(id)sender {
    self.lightSlider.value = [[UIScreen mainScreen] brightness];
    [UIView animateWithDuration:0.3 animations:^{
        if (self.smallBottomView.frame.origin.y<SCREEN_HEIGHT-10) {
            self.smallBottomViewBottomConstraint.constant = -142;
            [self.smallBottomView layoutIfNeeded];
        }
    }];
    [UIView animateWithDuration:0.3 animations:^{
                            //这里书写动画相关代码
                            if (self.bigBottomView.frame.origin.y>SCREEN_HEIGHT-10) {
                                self.bigBottomViewBottomConstraint.constant = 0;
                                [self.bigBottomView layoutIfNeeded];
                            }
                        } completion:^(BOOL finished) {
                            //动画结束后执行的代码块
                        }];
}
- (IBAction)doAnything:(id)sender {
    //如果bigBottomView在显示，点击的时候切换到smallBottomView
//    if (self.bigBottomView.frame.origin.y<SCREEN_HEIGHT-10) {
//        [UIView animateWithDuration:0.4 animations:^{
//            if (self.bigBottomView.frame.origin.y<SCREEN_HEIGHT-10) {
//                self.bigBottomViewBottomConstraint.constant = -205;
//                [self.bigBottomView layoutIfNeeded];
//            }
//        }];
//        [UIView animateWithDuration:0.4 delay:0.2 options:UIViewAnimationOptionLayoutSubviews animations:^{
//            if (self.smallBottomView.frame.origin.y>SCREEN_HEIGHT-10) {
//                self.smallBottomViewBottomConstraint.constant = 0;
//                [self.smallBottomView layoutIfNeeded];
//            }
//        } completion:^(BOOL finished) {
//            
//        }];
//    }
}
#pragma mark - 跳转到目录页
- (IBAction)toBookCat:(id)sender {
    ZMYcatalogueRootViewController *catal = [self.storyboard instantiateViewControllerWithIdentifier:@"ZMYcatalogueRootViewController"];
    catal.book = self.book;
    catal.readViewController = self;
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:catal];
    nav.transitioningDelegate = self;
    [self presentViewController:nav animated:YES completion:nil];
}
#pragma mark - 显示缓存下载页
- (IBAction)showBookDownloadView:(id)sender {
    if (!bookReadDownloadViewController) {
        bookReadDownloadViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"BookReadDownloadViewController"];
        bookReadDownloadViewController.transitioningDelegate = self;
        bookReadDownloadViewController.book = self.book;
    }
    [self presentViewController:bookReadDownloadViewController animated:YES completion:nil];
}

#pragma mark - 改变屏幕亮度
- (IBAction)lightChang:(id)sender {
    [[UIScreen mainScreen] setBrightness:self.lightSlider.value];
}
#pragma mark - 跳转目录页动画
-(id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
    self.animator.operation = UINavigationControllerOperationPush;
    return self.animator;
}
-(id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    self.animator.operation = UINavigationControllerOperationPop;
    return self.animator;
}
#pragma mark - 更改字体颜色
- (IBAction)ColorConfig0:(id)sender {
    [ReadConfig currentAccount].isBlack = NO;
    [self.linghtButton setImage:[UIImage imageNamed:@"textColorNight"] forState:UIControlStateNormal];
    [ReadConfig currentAccount].colorConfig = ColorConfig0;
//    if ([ReadConfig currentAccount].transitionStyle == TransitionStylePageCurl) {
        ReadPageViewController *currentViewController = self.pageViewController.viewControllers[0];
        [currentViewController changeColor];
    self.pageViewController.view.backgroundColor = [ReadConfig currentAccount].bgColor;
//    } else {
//        [self.horizontalSlidingViewController.collectionView reloadData];
//    }
}
- (IBAction)ColorConfig1:(id)sender {
    [ReadConfig currentAccount].isBlack = NO;
    [self.linghtButton setImage:[UIImage imageNamed:@"textColorNight"] forState:UIControlStateNormal];
    [ReadConfig currentAccount].colorConfig = ColorConfig1;
//    if ([ReadConfig currentAccount].transitionStyle == TransitionStylePageCurl) {
        ReadPageViewController *currentViewController = self.pageViewController.viewControllers[0];
        [currentViewController changeColor];
    self.pageViewController.view.backgroundColor = [ReadConfig currentAccount].bgColor;
//    } else {
//        [self.horizontalSlidingViewController.collectionView reloadData];
//    }
}
- (IBAction)ColorConfig2:(id)sender {
    [ReadConfig currentAccount].isBlack = NO;
    [self.linghtButton setImage:[UIImage imageNamed:@"textColorNight"] forState:UIControlStateNormal];
    [ReadConfig currentAccount].colorConfig = ColorConfig2;
//    if ([ReadConfig currentAccount].transitionStyle == TransitionStylePageCurl) {
        ReadPageViewController *currentViewController = self.pageViewController.viewControllers[0];
        [currentViewController changeColor];
    self.pageViewController.view.backgroundColor = [ReadConfig currentAccount].bgColor;
//    } else {
//        [self.horizontalSlidingViewController.collectionView reloadData];
//    }
}
- (IBAction)ColorConfig3:(id)sender {
    [ReadConfig currentAccount].isBlack = NO;
    [self.linghtButton setImage:[UIImage imageNamed:@"textColorNight"] forState:UIControlStateNormal];
    [ReadConfig currentAccount].colorConfig = ColorConfig3;
//    if ([ReadConfig currentAccount].transitionStyle == TransitionStylePageCurl) {
        ReadPageViewController *currentViewController = self.pageViewController.viewControllers[0];
        [currentViewController changeColor];
    self.pageViewController.view.backgroundColor = [ReadConfig currentAccount].bgColor;
//    } else {
//        [self.horizontalSlidingViewController.collectionView reloadData];
//    }
}
- (IBAction)ColorConfig4:(id)sender {
    [ReadConfig currentAccount].isBlack = NO;
    [self.linghtButton setImage:[UIImage imageNamed:@"textColorNight"] forState:UIControlStateNormal];
    [ReadConfig currentAccount].colorConfig = ColorConfig4;
//    if ([ReadConfig currentAccount].transitionStyle == TransitionStylePageCurl) {
        ReadPageViewController *currentViewController = self.pageViewController.viewControllers[0];
        [currentViewController changeColor];
    self.pageViewController.view.backgroundColor = [ReadConfig currentAccount].bgColor;
//    } else {
//        [self.horizontalSlidingViewController.collectionView reloadData];
//    }
}
- (IBAction)ColorConfig5:(id)sender {
    [ReadConfig currentAccount].isBlack = NO;
    [self.linghtButton setImage:[UIImage imageNamed:@"textColorNight"] forState:UIControlStateNormal];
    [ReadConfig currentAccount].colorConfig = ColorConfig5;
//    if ([ReadConfig currentAccount].transitionStyle == TransitionStylePageCurl) {
        ReadPageViewController *currentViewController = self.pageViewController.viewControllers[0];
        [currentViewController changeColor];
    self.pageViewController.view.backgroundColor = [ReadConfig currentAccount].bgColor;
//    } else {
//        [self.horizontalSlidingViewController.collectionView reloadData];
//    }
}
- (IBAction)ColorConfig6:(id)sender {
//    黑夜
    UIButton *button = sender;
    [ReadConfig currentAccount].isBlack = ![ReadConfig currentAccount].isBlack;
    if ([ReadConfig currentAccount].isBlack) {
        [button setImage:[UIImage imageNamed:@"textColorDay"] forState:UIControlStateNormal];
    }else{
        [button setImage:[UIImage imageNamed:@"textColorNight"] forState:UIControlStateNormal];
    }
//    if ([ReadConfig currentAccount].transitionStyle == TransitionStylePageCurl) {
        ReadPageViewController *currentViewController = self.pageViewController.viewControllers[0];
        [currentViewController changeColor];
//    } else {
//        [self.horizontalSlidingViewController.collectionView reloadData];
//    }
}
#pragma mark - 更改字体大小
- (IBAction)changeFoutSizeSmall:(id)sender {
    [ReadConfig currentAccount].foutSize -= 2;
    [self.modelController parseBookChapterText];
    NSRange rang = NSRangeFromString([[ZMYLKDB getLKDBHelper]getReadSchedule:self.book.articleid].rang);
    NSInteger item = [self.modelController getIndexItem:rang];
    ReadPageViewController *startingViewController = [self.modelController viewControllerAtIndex:item storyboard:self.storyboard];
    NSArray *viewControllers = @[startingViewController];
    [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
}
- (IBAction)changeFoutSizeBig:(id)sender {
    [ReadConfig currentAccount].foutSize += 2;
    [self.modelController parseBookChapterText];
    NSRange rang = NSRangeFromString([[ZMYLKDB getLKDBHelper]getReadSchedule:self.book.articleid].rang);
    NSInteger item = [self.modelController getIndexItem:rang];
    ReadPageViewController *startingViewController = [self.modelController viewControllerAtIndex:item storyboard:self.storyboard];
    NSArray *viewControllers = @[startingViewController];
    [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    
}
#pragma mark - 章节滑块
-(void)changePageSlile{
    ReadPageViewController *currentViewController = self.pageViewController.viewControllers[0];
    [currentViewController changeColor];
    CGFloat percent = (CGFloat)currentViewController.indexItem/(currentViewController.allItemNum-2);
    [self.progressSlider setValue:percent];
}
- (IBAction)pageScrollChange:(id)sender {
    ReadPageViewController *currentViewController = self.pageViewController.viewControllers[0];
    NSUInteger item = (currentViewController.allItemNum-2)*self.progressSlider.value-1;
    if (item!=currentViewController.indexItem) {
        NSLog(@"%@",[NSNumber numberWithInteger:item]);
        ReadPageViewController *startingViewController = [self.modelController viewControllerAtIndex:item storyboard:self.storyboard];
        NSArray *viewControllers = @[startingViewController];
        [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    }
}

#pragma mark 上一章
- (IBAction)beforeChapterShow:(id)sender {
    if (self.beforeChapterInfo) {
        if ([self.book.articleid hasPrefix:@"qiyou"]) {
            YiDongSubscription *subView = [[[NSBundle mainBundle]loadNibNamed:@"YiDongSubscription" owner:nil options:nil]lastObject];
            subView.chapterId = self.beforeChapterInfo.chapterId;
            subView.book= self.book;
            [subView beginVerificationReadPermissionsSucceed:^{
                BookChapterText *bookChapterText=[[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.book.articleid chapterId:self.beforeChapterInfo.chapterId];
                if (bookChapterText) {
                    //如果本地没有该章节内容
                    ReadSchedule *readSch = [ReadSchedule new];
                    readSch.articleid = self.book.articleid;
                    readSch.chapterId = self.beforeChapterInfo.chapterId;
                    readSch.rang = [NSString stringWithFormat:@"{%u,10}",bookChapterText.chapterTextString.length-20];
                    [[ZMYLKDB getLKDBHelper]updateReadSchedule:readSch];
                    [self changeToReadSchedule];
                    [AppDelegate hideAllHUD:[AppDelegate delegate].window];
                } else {
                    [AppDelegate showHUDAndHide:@"章节未找到" view:[AppDelegate delegate].window];                }
            } Fail:^{
                [AppDelegate hideAllHUD:[AppDelegate delegate].window];
                NSLog(@"新模块支付失败");
            } Cancel:^{
                [AppDelegate hideAllHUD:[AppDelegate delegate].window];
                NSLog(@"新模块支付取消");
            }];
        } else {
            DefaultSubscription *payview = [[DefaultSubscription alloc]init];
            payview.book = self.book;
            payview.chapterIds = @[self.beforeChapterInfo.chapterId,self.beforeChapterInfo.chapterId];
            [payview beginVerificationReadPermissionsSucceed:^{
                NSLog(@"新模块支付成功");
                BookChapterText *bookChapterText=[[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.book.articleid chapterId:self.beforeChapterInfo.chapterId];
                if (bookChapterText) {
                    //如果本地没有该章节内容
                    ReadSchedule *readSch = [ReadSchedule new];
                    readSch.articleid = self.book.articleid;
                    readSch.chapterId = self.beforeChapterInfo.chapterId;
                    readSch.rang = @"{0,10}";
                    [[ZMYLKDB getLKDBHelper]updateReadSchedule:readSch];
                    [self changeToReadSchedule];
                    [AppDelegate hideAllHUD:[AppDelegate delegate].window];
                } else {
                    [AppDelegate showHUDAndHide:@"章节未找到" view:[AppDelegate delegate].window];
                }
                
            } Fail:^{
                [AppDelegate hideAllHUD:[AppDelegate delegate].window];
                NSLog(@"新模块支付失败");
            } Cancel:^{
                [AppDelegate hideAllHUD:[AppDelegate delegate].window];
                NSLog(@"新模块支付取消");
            }];
        }
    } else {
        [AppDelegate showHUDAndHide:@"已到第一章" view:[AppDelegate delegate].window];
    }

}
#pragma mark 下一章
- (IBAction)nextChapterShow:(id)sender {
    if (self.nextChapterInfo) {
        if ([self.book.articleid hasPrefix:@"qiyou"]) {
            YiDongSubscription *subView = [[[NSBundle mainBundle]loadNibNamed:@"YiDongSubscription" owner:nil options:nil]lastObject];
            subView.chapterId = self.nextChapterInfo.chapterId;
            subView.book= self.book;
            [subView beginVerificationReadPermissionsSucceed:^{
                NSLog(@"新模块支付成功");
                BookChapterText *bookChapterText=[[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.book.articleid chapterId:self.nextChapterInfo.chapterId];
                if (bookChapterText) {
                    //如果本地没有该章节内容
                    ReadSchedule *readSch = [ReadSchedule new];
                    readSch.articleid = self.book.articleid;
                    readSch.chapterId = self.nextChapterInfo.chapterId;
                    readSch.rang = @"{0,10}";
                    [[ZMYLKDB getLKDBHelper]updateReadSchedule:readSch];
                    [self changeToReadSchedule];
                    [AppDelegate hideAllHUD:[AppDelegate delegate].window];
                } else {
                    [AppDelegate showHUDAndHide:@"章节未找到" view:[AppDelegate delegate].window];
                }
            } Fail:^{
                [AppDelegate hideAllHUD:[AppDelegate delegate].window];
                NSLog(@"新模块支付失败");
            } Cancel:^{
                [AppDelegate hideAllHUD:[AppDelegate delegate].window];
                NSLog(@"新模块支付取消");
            }];
        } else {
            DefaultSubscription *payview = [[DefaultSubscription alloc]init];
            payview.book = self.book;
            payview.chapterIds = @[self.nextChapterInfo.chapterId,self.nextChapterInfo.chapterId];
            [payview beginVerificationReadPermissionsSucceed:^{
                NSLog(@"新模块支付成功");
                BookChapterText *bookChapterText=[[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.book.articleid chapterId:self.nextChapterInfo.chapterId];
                if (bookChapterText) {
                    //如果本地没有该章节内容
                    ReadSchedule *readSch = [ReadSchedule new];
                    readSch.articleid = self.book.articleid;
                    readSch.chapterId = self.nextChapterInfo.chapterId;
                    readSch.rang = @"{0,10}";
                    [[ZMYLKDB getLKDBHelper]updateReadSchedule:readSch];
                    [self changeToReadSchedule];
                    [AppDelegate hideAllHUD:[AppDelegate delegate].window];
                } else {
                    [AppDelegate showHUDAndHide:@"章节未找到" view:[AppDelegate delegate].window];
                }
                
            } Fail:^{
                [AppDelegate hideAllHUD:[AppDelegate delegate].window];
                NSLog(@"新模块支付失败");
            } Cancel:^{
                [AppDelegate hideAllHUD:[AppDelegate delegate].window];
                NSLog(@"新模块支付取消");
            }];
        }
    } else {
        [AppDelegate showHUDAndHide:@"已到最后一章" view:[AppDelegate delegate].window];
    }
}
-(void)transitionToReadView:(NSString *)chapterId{
#pragma mark 切换到跳转章节
    ReadSchedule *readSch = [ReadSchedule new];
    readSch.articleid = self.book.articleid;
    readSch.chapterId = chapterId;
    readSch.rang = NSStringFromRange(NSMakeRange(0, 10));
    [[ZMYLKDB getLKDBHelper]updateReadSchedule:readSch];
    [self changeToReadSchedule];
}
#pragma mark - 更改翻页形式
- (IBAction)simulatPage:(id)sender {
    if ([ReadConfig currentAccount].transitionStyle == TransitionStyleScroll) {
        [ReadConfig currentAccount].transitionStyle = TransitionStylePageCurl;
//        if (self.pageViewController) {
//            [self.pageViewController willMoveToParentViewController:nil];
//            [self.pageViewController.view removeFromSuperview];
//            [self.pageViewController removeFromParentViewController];
//            self.pageViewController.delegate = nil;
//            self.pageViewController.dataSource = nil;
//            self.pageViewController = nil;
//            _modelController = nil;
//            self.view.gestureRecognizers = nil;
//        }
        [self changeToReadSchedule];
    }
}
- (IBAction)slidingPage:(id)sender {
    if ([ReadConfig currentAccount].transitionStyle == TransitionStylePageCurl) {
        [ReadConfig currentAccount].transitionStyle = TransitionStyleScroll;
//        if (self.pageViewController) {
//            [self.pageViewController willMoveToParentViewController:nil];
//            [self.pageViewController.view removeFromSuperview];
//            [self.pageViewController removeFromParentViewController];
//            self.pageViewController.delegate = nil;
//            self.pageViewController.dataSource = nil;
//            self.pageViewController = nil;
//            _modelController = nil;
//            self.view.gestureRecognizers = nil;
//        }
        [self changeToReadSchedule];
    }
}
- (IBAction)autoScrollSpeedChanged:(id)sender {
    self.autoReadViewController.pointsPerSecond = self.scrollSpeedSlider.value;
}
- (IBAction)autoRead:(id)sender {
    if (!isAutoScroll) {
        isAutoScroll = YES;
        [self barHidden];
        if (self.pageViewController) {
            [self.pageViewController willMoveToParentViewController:nil];
            [self.pageViewController.view removeFromSuperview];
            [self.pageViewController removeFromParentViewController];
            self.pageViewController.delegate = nil;
            self.pageViewController.dataSource = nil;
            self.pageViewController = nil;
            _modelController = nil;
            self.view.gestureRecognizers = nil;
        }
        self.autoReadViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ZMYAutoReadViewController"];
        self.autoReadViewController.articleid = self.book.articleid;
        self.autoReadViewController.delegate = self;
        [self addChildViewController:self.autoReadViewController];
        [self.groundView addSubview:self.autoReadViewController.view];
        CGRect pageViewRect = self.view.bounds;
        self.autoReadViewController.view.frame = pageViewRect;
        [self.autoReadViewController didMoveToParentViewController:self];
    }
}
- (IBAction)stopAutoScroll:(id)sender {//6221885131027123040
    if (isAutoScroll) {
        isAutoScroll = NO;
        [self barHidden];
        if (self.autoReadViewController) {
            [self.autoReadViewController willMoveToParentViewController:nil];
            [self.autoReadViewController.view removeFromSuperview];
            [self.autoReadViewController removeFromParentViewController];
            self.autoReadViewController.delegate = nil;
            self.autoReadViewController = nil;
        }
        [self changeToReadSchedule];
    }
    
}
@end
